/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUIRegistrarMovimiento.java
 *
 * Created on Oct 20, 2011, 2:26:15 AM
 */
package GUI.Procesamiento;

import BE.BECargo;
import GUI.Pallet.GUIAsignarPallets;
import BE.BEContacto;
import BE.BELineaMovimiento;
import BE.BEMovimiento;
import BE.BEPallet;
import BL.BLCardex;
import BL.BLPallet;
import BL.BLmovimiento;
import DA.DAContacto;
import GUI.Contactos.GUIMantenimientoContacto;
import GUI.Paleta.GUIMantenimientoPaleta;
import GUI.Pallet.GUIMantenimientoPallet;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author fenartcos
 */
public class GUIRegistrarIngreso extends javax.swing.JDialog {
    private BEMovimiento objMovimiento;
    private BEContacto objcontacto;
    private List<BELineaMovimiento> lineas=new ArrayList<BELineaMovimiento>();
    private BEPallet objpallet = new BEPallet();
    /** Creates novew form GUIRegistrarMovimiento */
    public GUIRegistrarIngreso(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int height = screenSize.height;
        int width = screenSize.width;
        this.setLocation(width/2-this.getWidth()/2, height/2-this.getHeight()/2);
       objMovimiento= new BEMovimiento();
        java.util.Date fecha = new Date();
        
        jDCfecha.setDate(fecha);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnCancelar = new javax.swing.JButton();
        pnlMovimiento = new javax.swing.JPanel();
        lblFecha = new javax.swing.JLabel();
        txtCliProv = new javax.swing.JTextField();
        lblCliProv = new javax.swing.JLabel();
        jDCfecha = new com.toedter.calendar.JDateChooser();
        btnBusqueda = new javax.swing.JButton();
        lbEmpresa = new javax.swing.JLabel();
        txtEmpresa = new javax.swing.JTextField();
        lbDocumento = new javax.swing.JLabel();
        txtDocIdent = new javax.swing.JTextField();
        btnAceptar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblRegMov = new javax.swing.JTable();
        btnAgregar = new javax.swing.JButton();
        btnRemover = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Registrar Internamiento");

        btnCancelar.setText("Cancelar");
        btnCancelar.setMaximumSize(new java.awt.Dimension(100, 25));
        btnCancelar.setMinimumSize(new java.awt.Dimension(100, 25));
        btnCancelar.setPreferredSize(new java.awt.Dimension(100, 25));
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        pnlMovimiento.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Generales"));

        lblFecha.setText("Fecha:");

        txtCliProv.setEnabled(false);
        txtCliProv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCliProvActionPerformed(evt);
            }
        });

        lblCliProv.setText("Proveedor:");

        jDCfecha.setEnabled(false);

        btnBusqueda.setText("...");
        btnBusqueda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBusquedaActionPerformed(evt);
            }
        });

        lbEmpresa.setText("Empresa:");

        txtEmpresa.setEnabled(false);

        lbDocumento.setText("Documento Ident. :");

        txtDocIdent.setEnabled(false);

        javax.swing.GroupLayout pnlMovimientoLayout = new javax.swing.GroupLayout(pnlMovimiento);
        pnlMovimiento.setLayout(pnlMovimientoLayout);
        pnlMovimientoLayout.setHorizontalGroup(
            pnlMovimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlMovimientoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlMovimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblCliProv)
                    .addComponent(lblFecha)
                    .addComponent(lbEmpresa)
                    .addComponent(lbDocumento))
                .addGap(25, 25, 25)
                .addGroup(pnlMovimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtDocIdent, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)
                    .addGroup(pnlMovimientoLayout.createSequentialGroup()
                        .addComponent(txtCliProv, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jDCfecha, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)
                    .addComponent(txtEmpresa, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE))
                .addGap(278, 278, 278))
        );
        pnlMovimientoLayout.setVerticalGroup(
            pnlMovimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlMovimientoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlMovimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCliProv)
                    .addComponent(txtCliProv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBusqueda))
                .addGap(9, 9, 9)
                .addGroup(pnlMovimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblFecha)
                    .addComponent(jDCfecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(pnlMovimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbEmpresa)
                    .addComponent(txtEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(pnlMovimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbDocumento)
                    .addComponent(txtDocIdent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        btnAceptar.setText("Siguiente");
        btnAceptar.setMaximumSize(new java.awt.Dimension(100, 25));
        btnAceptar.setMinimumSize(new java.awt.Dimension(100, 25));
        btnAceptar.setPreferredSize(new java.awt.Dimension(100, 25));
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        tblRegMov.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Movimiento", "Linea", "Pallet", "Producto", "Proveedor", "Fecha Venc.", "Cantidad"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblRegMov.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        tblRegMov.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tblRegMov);
        tblRegMov.getColumnModel().getColumn(0).setMinWidth(0);
        tblRegMov.getColumnModel().getColumn(0).setPreferredWidth(0);
        tblRegMov.getColumnModel().getColumn(0).setMaxWidth(0);
        tblRegMov.getColumnModel().getColumn(1).setMinWidth(0);
        tblRegMov.getColumnModel().getColumn(1).setPreferredWidth(0);
        tblRegMov.getColumnModel().getColumn(1).setMaxWidth(0);
        tblRegMov.getColumnModel().getColumn(5).setMinWidth(0);
        tblRegMov.getColumnModel().getColumn(5).setPreferredWidth(0);
        tblRegMov.getColumnModel().getColumn(5).setMaxWidth(0);

        btnAgregar.setText("Agregar");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnRemover.setText("Remover");
        btnRemover.setMaximumSize(new java.awt.Dimension(100, 25));
        btnRemover.setMinimumSize(new java.awt.Dimension(100, 25));
        btnRemover.setPreferredSize(new java.awt.Dimension(100, 25));
        btnRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoverActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAgregar)
                        .addGap(13, 13, 13)
                        .addComponent(btnRemover, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(pnlMovimiento, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAceptar, btnAgregar, btnCancelar});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlMovimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAgregar)
                    .addComponent(btnRemover, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnAceptar, btnAgregar, btnCancelar});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void txtCliProvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCliProvActionPerformed

    }//GEN-LAST:event_txtCliProvActionPerformed

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
    if (lineas.size()==0)
            JOptionPane.showMessageDialog(null,"Debe agregar un pallet",
                                              "Informacion",JOptionPane.INFORMATION_MESSAGE);
    else{
    //       lineas.get(0).setDescripcion(tblRegMov.getModel().getValueAt(0,5).toString());
    objMovimiento.setContacto(objcontacto);
    objMovimiento.setDetalleMovimiento(lineas);
    objMovimiento.setEstado("1");
    java.util.Date fecha = new Date();
    objMovimiento.setFecha(fecha);
    //objMovimiento.setDescripcion(txtDescripcion.getText());

    
    //BLmovimiento blmov = new BLmovimiento();
    //blmov.agregarInternamiento(objMovimiento);


        GUIP1BuscarPosicionesInternamiento dlgP1BuscarPosiciones = new GUIP1BuscarPosicionesInternamiento(null, true,objpallet,objMovimiento,objcontacto);
        this.setVisible(false);
        dlgP1BuscarPosiciones.setResizable(false);
        dlgP1BuscarPosiciones.setVisible(true);
        this.dispose();

        }


    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed

        if (txtCliProv.getText().length()==0)
        { JOptionPane.showMessageDialog(null,"Debe seleccionar un Proveedor",
                                          "Informacion",JOptionPane.INFORMATION_MESSAGE);
          return;
        }
   if (lineas.size()>0)
        JOptionPane.showMessageDialog(null,"Solo puede agregar un pallet",
                                          "Informacion",JOptionPane.INFORMATION_MESSAGE);
  else{
        GUIMantenimientoPallet frmAsignarPallet= new GUIMantenimientoPallet(null,true,objcontacto);
        frmAsignarPallet.setVisible(true);
        objpallet= new BEPallet();
        objpallet=frmAsignarPallet.getObjPallet();
        

        BELineaMovimiento linea=new BELineaMovimiento();
        
        if (objpallet!=null  && objpallet.getIdPallet()>0){
        objpallet.setEstado("UBICADO");

        linea.setPallet(objpallet);
       linea.setCantidad(objpallet.getCantidad()) ;
        lineas.add(linea);
       llenarTabla(lineas);
        }

        frmAsignarPallet.dispose();

        }
        // TODO add your handling code here:
    }//GEN-LAST:event_btnAgregarActionPerformed

    public void llenarTabla(List <BELineaMovimiento> lista){

   DefaultTableModel modelo=(DefaultTableModel) tblRegMov.getModel();
for (int i=modelo.getRowCount()-1;i>=0;i--){
    modelo.removeRow(i);
}
BEContacto objContacto= new BEContacto();
DAContacto dacontacto= new DAContacto();


if (lista!=null){
    for (int i = 0; i < lista.size(); i++) {
        modelo.addRow(new Object[5]);
        tblRegMov.setValueAt(lista.get(i).getIdLineaMovimiento(), i, 0);

        tblRegMov.setValueAt(lista.get(i).getIdmovimiento(), i, 1);
        tblRegMov.setValueAt(lista.get(i).getPallet().getIdPallet(), i, 2);

 tblRegMov.setValueAt(lista.get(i).getPallet().getProducto().getNombre(), i, 3);
 tblRegMov.setValueAt(lista.get(i).getPallet().getFechaVencimiento().toString(), i, 5);
objContacto=dacontacto.getContactobyId(lista.get(i).getPallet().getProducto().getIdProveedor());

        tblRegMov.setValueAt(objcontacto.getNombEmpresa(), i, 4);
        tblRegMov.setValueAt(lista.get(i).getPallet().getCantidad(), i, 6);
    }
    }
}




    private void btnBusquedaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBusquedaActionPerformed
       GUIMantenimientoContacto frmBuscarContacto= new GUIMantenimientoContacto (null,true,objcontacto);
        frmBuscarContacto.setVisible(true);
        objcontacto= frmBuscarContacto.getObjEmpleado();
        //System.out.println("+++++++++"+objcontacto.getNombre()+"+++++++++++");
        BLPallet blpallet = new BLPallet();

        
        if (objcontacto!=null){
            //estos metodos los puedo cambiar por simples validaciones....
        if (blpallet.proveedorTienePalletsAsignados(objcontacto.getIdPersona()) )
        
        {
            txtCliProv.setText(objcontacto.getNombre());
            txtEmpresa.setText(objcontacto.getNombEmpresa());
            txtDocIdent.setText(objcontacto.getNroDocumento()+"");
        }
        else 
        {
            JOptionPane.showMessageDialog(null,"El proveedor seleccionado no tiene pallets asignados","Informacion",JOptionPane.INFORMATION_MESSAGE);
        }
            
        }


        frmBuscarContacto.dispose();
        
        

    }//GEN-LAST:event_btnBusquedaActionPerformed

    private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
       lineas.clear();

      llenarTabla(lineas);

    }//GEN-LAST:event_btnRemoverActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUIRegistrarIngreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUIRegistrarIngreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUIRegistrarIngreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUIRegistrarIngreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                GUIRegistrarIngreso dialog = new GUIRegistrarIngreso(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnBusqueda;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnRemover;
    private com.toedter.calendar.JDateChooser jDCfecha;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbDocumento;
    private javax.swing.JLabel lbEmpresa;
    private javax.swing.JLabel lblCliProv;
    private javax.swing.JLabel lblFecha;
    private javax.swing.JPanel pnlMovimiento;
    private javax.swing.JTable tblRegMov;
    private javax.swing.JTextField txtCliProv;
    private javax.swing.JTextField txtDocIdent;
    private javax.swing.JTextField txtEmpresa;
    // End of variables declaration//GEN-END:variables
}
